package com.qf.elasticsearch.index.impl;

import com.qf.elasticsearch.index.IndexService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.admin.indices.get.GetIndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * create by 郑大仙丶
 * 2019/11/21 0:24
 */
@Service
@Slf4j
public class IndexServiceImpl implements IndexService {

    @Autowired
    private RestHighLevelClient client;


    @Override
    public void createIndex(String index, CreateIndexRequest request) throws IOException {
        //1. 判断节点是否存在.
        if(!existsIndex(index)){
            //2.1 不存在创建
            client.indices().create(request, RequestOptions.DEFAULT);
        }else{
            //2.2 存在不创建
            log.warn("节点不存在,无法创建 index = {}",index);
        }
    }

    @Override
    public void deleteIndex(String index) throws IOException {
        //1. 查看节点是否存在
        if(existsIndex(index)){
            //2. 创建删除节点请求对象
            DeleteIndexRequest request = new DeleteIndexRequest();
            //3. 设置删除的index
            request.indices(index);
            //4. 使用客户端执行删除
            client.indices().delete(request,RequestOptions.DEFAULT);
        }
    }

    @Override
    public boolean existsIndex(String index) throws IOException {
        //1. 创建查看索引的请求对象
        GetIndexRequest request = new GetIndexRequest();
        //2. 设置查看的index
        request.indices(index);
        //3. 调用客户端执行
        boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
        //4. 返回boolean   存在返回true
        return exists;
    }
}
